/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.ws.jackson;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.foreveross.bsl.common.utils.ws.jackson.mixins.OrderMixin;
import com.foreveross.bsl.common.utils.ws.jackson.mixins.PageMixin;
import com.foreveross.bsl.common.utils.ws.jackson.mixins.PageRequestMixin;
import com.foreveross.bsl.common.utils.ws.jackson.mixins.PageableMixin;
import com.foreveross.bsl.common.utils.ws.jackson.mixins.SortMixin;


/**
 * 在Spring3.1中我没找到关于Jackson2的FactoryBean，于是从3.2的版本中拷贝一个，并增加了对spring-data常用数据接口和类(Page,Pageable等)的mixin
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-7-26
 *
 */
public class Jackson2ObjectMapperFactoryBean implements FactoryBean<ObjectMapper>, InitializingBean {

	private ObjectMapper objectMapper;

	private Map<Object, Boolean> features = new HashMap<Object, Boolean>();

	private DateFormat dateFormat;

	private AnnotationIntrospector annotationIntrospector;

	private final Map<Class<?>, JsonSerializer<?>> serializers = new LinkedHashMap<Class<?>, JsonSerializer<?>>();

	private final Map<Class<?>, JsonDeserializer<?>> deserializers = new LinkedHashMap<Class<?>, JsonDeserializer<?>>();
	
	private final Map<Class<?>, Class<?>> mixins= new LinkedHashMap<Class<?>, Class<?>>();


	/**
	 * Set the ObjectMapper instance to use. If not set, the ObjectMapper will
	 * be created using its default constructor.
	 */
	public void setObjectMapper(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	/**
	 * Define the format for date/time with the given {@link DateFormat}.
	 * @see #setSimpleDateFormat(String)
	 */
	public void setDateFormat(DateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}

	/**
	 * Define the date/time format with a {@link SimpleDateFormat}.
	 * @see #setDateFormat(DateFormat)
	 */
	public void setSimpleDateFormat(String format) {
		this.dateFormat = new SimpleDateFormat(format);
	}

	/**
	 * Set the {@link AnnotationIntrospector} for both serialization and
	 * deserialization.
	 */
	public void setAnnotationIntrospector(AnnotationIntrospector annotationIntrospector) {
		this.annotationIntrospector = annotationIntrospector;
	}

	/**
	 * Configure custom serializers. Each serializer is registered for the type
	 * returned by {@link JsonSerializer#handledType()}, which must not be
	 * {@code null}.
	 * @see #setSerializersByType(Map)
	 */
	public void setSerializers(JsonSerializer<?>... serializers) {
		if (serializers != null) {
			for (JsonSerializer<?> serializer : serializers) {
				Class<?> handledType = serializer.handledType();
				Assert.isTrue(handledType != null && handledType != Object.class,
						"Unknown handled type in " + serializer.getClass().getName());
				this.serializers.put(serializer.handledType(), serializer);
			}
		}
	}

	/**
	 * Configure custom serializers for the given types.
	 * @see #setSerializers(JsonSerializer...)
	 */
	public void setSerializersByType(Map<Class<?>, JsonSerializer<?>> serializers) {
		if (serializers != null) {
			this.serializers.putAll(serializers);
		}
	}

	/**
	 * Configure custom deserializers for the given types.
	 */
	public void setDeserializersByType(Map<Class<?>, JsonDeserializer<?>> deserializers) {
		if (deserializers != null) {
			this.deserializers.putAll(deserializers);
		}
	}

	/**
	 * Shortcut for {@link MapperFeature#AUTO_DETECT_FIELDS} option.
	 */
	public void setAutoDetectFields(boolean autoDetectFields) {
		this.features.put(MapperFeature.AUTO_DETECT_FIELDS, autoDetectFields);
	}

	/**
	 * Shortcut for {@link MapperFeature#AUTO_DETECT_SETTERS}/
	 * {@link MapperFeature#AUTO_DETECT_GETTERS} option.
	 */
	public void setAutoDetectGettersSetters(boolean autoDetectGettersSetters) {
		this.features.put(MapperFeature.AUTO_DETECT_SETTERS, autoDetectGettersSetters);
		this.features.put(MapperFeature.AUTO_DETECT_GETTERS, autoDetectGettersSetters);
	}

	/**
	 * Shortcut for {@link SerializationFeature#FAIL_ON_EMPTY_BEANS} option.
	 */
	public void setFailOnEmptyBeans(boolean failOnEmptyBeans) {
		this.features.put(SerializationFeature.FAIL_ON_EMPTY_BEANS, failOnEmptyBeans);
	}

	/**
	 * Shortcut for {@link SerializationFeature#INDENT_OUTPUT} option.
	 */
	public void setIndentOutput(boolean indentOutput) {
		this.features.put(SerializationFeature.INDENT_OUTPUT, indentOutput);
	}

	/**
	 * Specify features to enable.
	 *
	 * @see MapperFeature
	 * @see SerializationFeature
	 * @see DeserializationFeature
	 * @see org.codehaus.jackson.map.JsonParser.Feature
	 * @see org.codehaus.jackson.map.JsonGenerator.Feature
	 */
	public void setFeaturesToEnable(Object... featuresToEnable) {
		if (featuresToEnable != null) {
			for (Object feature : featuresToEnable) {
				this.features.put(feature, Boolean.TRUE);
			}
		}
	}

	/**
	 * Specify features to disable.
	 *
	 * @see MapperFeature
	 * @see SerializationFeature
	 * @see DeserializationFeature
	 * @see org.codehaus.jackson.map.JsonParser.Feature
	 * @see org.codehaus.jackson.map.JsonGenerator.Feature
	 */
	public void setFeaturesToDisable(Object... featuresToDisable) {
		if (featuresToDisable != null) {
			for (Object feature : featuresToDisable) {
				this.features.put(feature, Boolean.FALSE);
			}
		}
	}

	public void afterPropertiesSet() throws FatalBeanException {
		if (this.objectMapper == null) {
			this.objectMapper = new ObjectMapper();
		}

		if (this.dateFormat != null) {
			this.objectMapper.setDateFormat(this.dateFormat);
		}

		if (this.serializers != null || this.deserializers != null) {
			SimpleModule module = new SimpleModule();
			addSerializers(module);
			addDeserializers(module);
			this.objectMapper.registerModule(module);
		}

		if (this.annotationIntrospector != null) {
			this.objectMapper.setAnnotationIntrospector(this.annotationIntrospector);
		}

		for (Object feature : this.features.keySet()) {
			configureFeature(feature, this.features.get(feature));
		}
		
		if(this.mixins!=null && !this.mixins.isEmpty()){
			for(Map.Entry<Class<?>, Class<?>> entry : this.mixins.entrySet()){
				this.objectMapper.addMixInAnnotations(entry.getKey(), entry.getValue());
			}
		}
		//默认加入对spring-data的一些常用数据接口和类的mixin
		this.addSpringDataMixins();
	}
	
	private void addSpringDataMixins(){
		this.objectMapper.addMixInAnnotations(Page.class, PageMixin.class);
		this.objectMapper.addMixInAnnotations(Pageable.class, PageableMixin.class);
		this.objectMapper.addMixInAnnotations(PageRequest.class, PageRequestMixin.class);
		this.objectMapper.addMixInAnnotations(Sort.class, SortMixin.class);
		this.objectMapper.addMixInAnnotations(Sort.Order.class, OrderMixin.class);
	}

	@SuppressWarnings("unchecked")
	private <T> void addSerializers(SimpleModule module) {
		for (Class<?> type : this.serializers.keySet()) {
			module.addSerializer((Class<? extends T>) type, (JsonSerializer<T>) this.serializers.get(type));
		}
	}

	@SuppressWarnings("unchecked")
	private <T> void addDeserializers(SimpleModule module) {
		for (Class<?> type : this.deserializers.keySet()) {
			module.addDeserializer((Class<T>) type, (JsonDeserializer<? extends T>) this.deserializers.get(type));
		}
	}

	private void configureFeature(Object feature, boolean enabled) {
		if (feature instanceof MapperFeature) {
			this.objectMapper.configure((MapperFeature) feature, enabled);
		}
		else if (feature instanceof DeserializationFeature) {
			this.objectMapper.configure((DeserializationFeature) feature, enabled);
		}
		else if (feature instanceof SerializationFeature) {
			this.objectMapper.configure((SerializationFeature) feature, enabled);
		}
		else if (feature instanceof JsonParser.Feature) {
			this.objectMapper.configure((JsonParser.Feature) feature, enabled);
		}
		else if (feature instanceof JsonGenerator.Feature) {
			this.objectMapper.configure((JsonGenerator.Feature) feature, enabled);
		}
		else {
			throw new FatalBeanException("Unknown feature class " + feature.getClass().getName());
		}
	}
	
	public void setMixins(Map<Class<?>, Class<?>> mixins){
		if(mixins!=null){
			this.mixins.putAll(mixins);
		}
	}

	/**
	 * Return the singleton ObjectMapper.
	 */
	public ObjectMapper getObject() {
		return this.objectMapper;
	}

	public Class<?> getObjectType() {
		return ObjectMapper.class;
	}

	public boolean isSingleton() {
		return true;
	}

}
